package com.webcamtracker.image.grid;

import com.webcamtracker.configuration.RootPref;
import com.webcamtracker.tracker.model.ModelElement;

import java.awt.image.BufferedImage;
import java.util.logging.Logger;
import java.util.prefs.Preferences;

public class ImageGrid {
    private BufferedImage image;
    private ModelElement[][] cells;
    public static Logger loger = Logger.getAnonymousLogger();
    private static final Preferences GRID_PREF = RootPref.getGridPref();

    public ImageGrid(BufferedImage image) {
        this.image = image;
        int x = image.getWidth() / getCellWidth();
        int y = image.getHeight() / getCellHeight();
        cells = new ModelElement[x][y];
    }

    public int getCellHeight() {
        return GRID_PREF.getInt(RootPref.KEY_GRID_HEIGHT, RootPref.DEF_VALUE_GRID_HEIGHT);
    }

    public int getCellWidth() {
        return GRID_PREF.getInt(RootPref.KEY_GRID_WIDTH, RootPref.DEF_VALUE_GRID_WIDTH);
    }


    private ModelElement get(int x, int y) {
        if (cells[x][y] == null) {
            cells[x][y] = buildElement(x, y);
        }
        return cells[x][y];
    }

    public boolean wasAnalized(int x, int y) {
        if (x >= cells.length) {
            System.out.println("(ImageGrid) X se va de rango " + x);
        }
        if (y >= cells[0].length) {
            System.out.println("(ImageGrid) Y se va de rango " + y);
        }
        return cells[x][y] != null;
    }

    public int getWidthInCell() {
        return cells.length;
    }

    public int getHeightInCell() {
        return cells[0].length;
    }

    private ModelElement buildElement(int x, int y) {
        int width = GRID_PREF.getInt(RootPref.KEY_GRID_WIDTH, RootPref.DEF_VALUE_GRID_WIDTH);
        int heigth = GRID_PREF.getInt(RootPref.KEY_GRID_HEIGHT, RootPref.DEF_VALUE_GRID_HEIGHT);
        int xpos = x * width;
        int ypos = y * heigth;

        return new ModelElement(getImage(), xpos, ypos, width, heigth);
    }

    public BufferedImage getImage() {
        return image;
    }

    public ModelElement get(double x, double y) {
        return get((int) x, (int) y);
    }

}
